package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"mini/model/mysql"
	"mini/model/redis"
	"strconv"
	"time"

	"mini/minirpc/internal/svc"
	"mini/minirpc/minirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductListLogic) ProductList(in *minirpc.ProductListRequest) (*minirpc.ProductListResponse, error) {
	// todo: add your logic here and delete this line

	var project []mysql.Products
	var count int64
	var sli []*minirpc.Project
	result, err := redis.Rdb.Get("projectlist" + strconv.Itoa(int(in.Page)) + strconv.Itoa(int(in.PageSize)) + in.Name).Result()
	s, _ := redis.Rdb.Get("sumList").Result()
	if err != nil {
		query := mysql.DB.Debug().Model(&mysql.Products{})

		if in.Name != "" {
			query = query.Where("name like ?", in.Name)
		}

		query.Count(&count)

		offset := (in.Page - 1) * in.PageSize

		if in.OrderBy != "" {
			order := in.OrderBy
			if in.SortOrder == "desc" || in.SortOrder == "DESC" {
				order += in.SortOrder
			} else {
				order += "asc"
			}
			query = query.Order(order)
		} else {
			query = query.Order("`like` DESC")
		}
		query.Offset(int(offset)).Limit(int(in.PageSize)).Find(&project)

		marshal, _ := json.Marshal(&project)
		bytes, _ := json.Marshal(&count)
		fmt.Println("走mysql")
		redis.Rdb.Set("projectlist"+strconv.Itoa(int(in.Page))+strconv.Itoa(int(in.PageSize))+in.Name, string(marshal), time.Hour*24)
		redis.Rdb.Set("sumList", string(bytes), time.Hour*24)
	} else {
		json.Unmarshal([]byte(result), &project)
		json.Unmarshal([]byte(s), &count)
		fmt.Println("走redis")
	}
	for _, m := range project {
		one := minirpc.Project{
			Image:  m.Image,
			Video:  m.Video,
			Name:   m.Name,
			Num:    m.Num,
			WhyBuy: m.WhyBuy,
			UserId: int64(m.UserId),
		}
		sli = append(sli, &one)
	}
	return &minirpc.ProductListResponse{Project: sli, Sum: count}, nil
}
